package com.ytzq.base.log;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.ytzq.base.constants.LOG_TYPE;
import com.ytzq.base.jdbc.DBConfigure;
/**
 * 将日子写入数据库（不能直接使用）
 * @author 门士松 20121206
 * @version 1.0 
 */
public class LogToDB {
	
	//日志内部处理不能用自定义日志，不然递归调用错误java.lang.StackOverflowError
	private Logger logger  = Logger.getLogger(this.getClass()); 	
	/**
	 * 插入日志信息
	 * @param log 日志对象
	 * @return 插入条数
	 */
	public int insertLogInfo(Log log) {	
		int flag = 0;	
		String sql="insert into T_SYS_LOG (source,type,title,description,class,ip,user_id,create_date) " +
				"values (?,?,?,?,?,?,?,getdate())";
		//标题的数据库字段，最多500个字符
		if(log.getTitle().length()>500){ 
			log.setTitle(log.getTitle().substring(0, 500));	
		}
		//详情的数据库字段，最多4000个字符
		if(log.getContent().length()>4000){ 
			log.setContent(log.getContent().substring(0, 4000));	
		}
		Connection conn = null;
		PreparedStatement pstmt = null;	 
        try{
			Object[] args = new Object[]{log.getSource(),log.getType(),log.getTitle(),log.getContent(),log.getGrade(),log.getIp(),log.getUserID()};
			conn = DBConfigure.getDataSource().getConnection();
            pstmt = conn.prepareStatement(sql);
            if (args != null){
                for (int i = 1; i <= args.length; i++){
                    pstmt.setObject(i, args[i - 1]);
                }
            }
    		flag = pstmt.executeUpdate();
        }catch (SQLException ex){
        	logger.error(LOG_TYPE.SYSTEM, ex);
        }finally{
            try{
                if (pstmt != null){
                	pstmt.close();
                }
                if (conn !=null){
                	conn.close();
                }
            }catch (Exception ex){
            	logger.error(LOG_TYPE.SYSTEM, ex); 
            }
        }		
		return flag;
	}
}
